#include "../include/threadPool.h"
#include "../include/encode.h"
#include "../include/decode.h"

int getToken(char *userName, char *token, char *secretKey){
    // 需要下载l8w8jwt库
    // 密钥可以自定义
    char* jwt;// 得到jwt->token                                                                                           
    size_t jwt_length;
    printf("10\n");
    struct l8w8jwt_encoding_params params;
    l8w8jwt_encoding_params_init(&params);
    printf("13\n");
    params.alg = L8W8JWT_ALG_HS512;

    params.sub = "User";
    params.iss = userName;        
    params.aud = "Client";

    params.iat = l8w8jwt_time(NULL);
    params.exp = l8w8jwt_time(NULL) + 600; /* Set to expire after 10 minutes (600 seconds). */

    params.secret_key = (unsigned char*)secretKey;
    params.secret_key_length = strlen((char *)params.secret_key);

    params.out = &jwt;            
    params.out_length = &jwt_length;
    int r = l8w8jwt_encode(&params);
    printf("29\n");
    //printf("\n l8w8jwt example HS512 token: %s \n", r == L8W8JWT_SUCCESS ? jwt : " (encoding failure) ");
    if(r == L8W8JWT_SUCCESS){
        strcpy(token,jwt);                              
    }else{
        printf("getTokenFailed\n");
    }
    printf("%s\n",jwt);
    printf("%s\n",token);
    /* Always free the output jwt string! */
    l8w8jwt_free(jwt);
    return 0;
}

int userTokenDecode(const char *token,const char *secretKey,char *userName){
    struct l8w8jwt_decoding_params params;
    l8w8jwt_decoding_params_init(&params);

    params.alg = L8W8JWT_ALG_HS512;

    params.jwt = (char*)token;
    params.jwt_length = strlen(token);

    params.verification_key = (unsigned char*)secretKey;
    params.verification_key_length = strlen(secretKey);

    /* 
     * Not providing params.validate_iss_length makes it use strlen()
     * Only do this when using properly NUL-terminated C-strings! 
     */
    params.validate_iss = userName; 
    params.validate_sub = "User";

    /* Expiration validation set to false here only because the above example token is already expired! */
    params.validate_exp = 0; 
    params.exp_tolerance_seconds = 60;

    params.validate_iat = 1;
    params.iat_tolerance_seconds = 60;

    enum l8w8jwt_validation_result validation_result;

    int decode_result = l8w8jwt_decode(&params, &validation_result, NULL, NULL);

    if (decode_result == L8W8JWT_SUCCESS && validation_result == L8W8JWT_VALID){ 
        printf("\n Example HS512 token validation successful! \n");
    }
    else{
        printf("\n Example HS512 token validation failed! \n");
    }
    return 0; 

}

//int main(){
//    char token[1024] = {0};
//    getToken("playba",token,"FuCk YoU");
//    printf("token = %s\n",token);
//    userTokenDecode(token,"FuCk YoU","playba");
//    return 0;
//}

